package com.dome.fastds.demofastds.controller;
/**
 * @author 莫耀华
 * @date 2021-12-20 22:03
 */

import com.dome.fastds.demofastds.utils.FastDFSUtils;
import com.dome.fastds.demofastds.utils.ResultUtil;
import org.apache.commons.lang.exception.ExceptionUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.apache.tomcat.util.http.fileupload.util.Streams;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.*;
import java.io.*;

/**
 * @ClassName FileController
 * @Description
 * @Author 莫耀华
 * @Date 2021/12/20 22:03
 * @Version 1.0
 */

/**
 *     "group1",
 *         "M00/00/00/rBRbt2HBOwSAJnDlAAAMPhxZC3Y542.txt"
 */
@RequestMapping("/file")
@RestController
public class FileController {

    private static final Logger logger = LoggerFactory.getLogger(FileController.class);
    //在文件操作中，不用/或者\最好，推荐使用File.separator
    private final static String FILE_DIR = "files";
    private final static String ROOT_PATH = System.getProperty("user.home") + File.separator + FILE_DIR + File.separator;

    @RequestMapping("/upload")
    public Object uploadFile(@RequestParam("file") MultipartFile[] multipartFiles, final HttpServletResponse response, final HttpServletRequest request) {
        File fileDir = new File(ROOT_PATH);
        if (!fileDir.exists() && !fileDir.isDirectory()) {
            fileDir.mkdirs();
        }
        try {
            if (multipartFiles != null && multipartFiles.length > 0) {
                for (int i = 0; i < multipartFiles.length; i++) {
                    try {
                        //以原来的名称命名,覆盖掉旧的
                        String storagePath = ROOT_PATH + multipartFiles[i].getOriginalFilename();
                        logger.info("上传的文件：" + multipartFiles[i].getName() + "," + multipartFiles[i].getContentType() + "," + multipartFiles[i].getOriginalFilename()
                                + "，保存的路径为：" + storagePath);
                        Streams.copy(multipartFiles[i].getInputStream(), new FileOutputStream(storagePath), true);
                        //或者下面的
                        // Path path = Paths.get(storagePath);
                        // Files.write(path,multipartFiles[i].getBytes());
                        String[] upload = FastDFSUtils.upload(multipartFiles[i]);
                        return ResultUtil.success(upload);
                    } catch (IOException e) {
                        logger.error(ExceptionUtils.getFullStackTrace(e));
                    }
                }
            }

        } catch (Exception e) {
            return ResultUtil.error(e.getMessage());
        }
        return ResultUtil.success("上传成功!");
    }


    @RequestMapping("/download")
    public Object downloadFile(@RequestParam String fileName, final HttpServletResponse response, final HttpServletRequest request) {
        InputStream is = null;
        try {
            // 清空输出流
            response.reset();
            response.setContentType("application/x-download;charset=GBK");
            response.setHeader("Content-Disposition", "attachment;filename=" + new String(fileName.getBytes("utf-8"), "iso-8859-1"));
            is=FastDFSUtils.downFile("group1","M00/00/00/rBRbt2HBOwSAJnDlAAAMPhxZC3Y542.txt");
            IOUtils.copy(is, response.getOutputStream());
            response.getOutputStream().flush();
        } catch (IOException e) {
            return ResultUtil.error("下载附件失败,error:" + e.getMessage());
        }
        //文件的关闭放在finally中
        finally {
            try {
                if (is != null) {
                    is.close();
                }
            } catch (IOException e) {
                logger.error(ExceptionUtils.getFullStackTrace(e));
            }
        }


        return ResultUtil.success("上传成功!");
    }

    @RequestMapping("/d")
    public void downloadFile1(@RequestParam String fileName, final HttpServletResponse response, final HttpServletRequest request) {
    }

    @RequestMapping("/get")
    public Object downloadFile1(HttpSession session) {
        return session.getAttribute("name");
    }
    @RequestMapping("/set")
    public void downloadFile1(HttpSession session, HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        session.setAttribute("name",cookies);
    }
}
